#include "weathernetwork.h"
#include <QDebug>
#include <widget.h>
#include <QFile>

WeatherNetWork::WeatherNetWork(Widget *parent)
    : QObject(parent)
    , _parent(parent)
{
    _manager = new QNetworkAccessManager(this);
    connect(_manager, &QNetworkAccessManager::finished, this, &WeatherNetWork::onNetworkReply);
    this->initMap();
    this->getWeatherData();
}

void WeatherNetWork::getWeatherData(const QString& city)
{
    QString cityCode = "";
    QString url = URL;
    if (city.size()) {
        cityCode = this->getCityCode(city);
        if (cityCode.size()) {
            url += "&cityid=" + cityCode;
        }
    }
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    _manager->get(request);
}

void WeatherNetWork::initMap()
{
    _qualityMap["优"] = "rgb(121, 184, 0)";
    _qualityMap["良"] = "rgb(255, 187, 23)";
    _qualityMap["轻度污染"] = "rgb(255, 87, 97)";
    _qualityMap["中度污染"] = "rgb(255, 17, 27)";
    _qualityMap["重度污染"] = "rgb(235, 0, 0)";
    _qualityMap["严重污染"] = "rgb(160, 0, 0)";

    _weatherMap.insert("暴雪", ":/res/BaoXue.png");
    _weatherMap.insert("暴雨", ":/res/BaoYu. png");
    _weatherMap.insert("暴雨到大暴雨", ":/res/BaoYuDaoDaBaoYu.png");
    _weatherMap.insert("大暴雨", ":/res/DaBaoYu.png");
    _weatherMap.insert("大暴雨到特大暴雨", ":/res/DaBaoYuDaoTeDaBaoYu.png");
    _weatherMap.insert("大到暴雪", ":/res/DaDaoBaoXue.png");
    _weatherMap.insert("大雪", ":/res/DaXue.png");
    _weatherMap.insert("大雨", ":/res/DaYu.png");
    _weatherMap.insert("冻雨", ":/res/DongYu.png");
    _weatherMap.insert("多云", ":/res/DuoYun.png");
    _weatherMap.insert("浮沉", ":/res/FuChen.png");
    _weatherMap.insert("雷阵雨", ":/res/LeiZhenYu.png");
    _weatherMap.insert("雷阵雨伴有冰雹", ":/res/LeiZhenYuBanYouBingBao.png");
    _weatherMap.insert("霾", ":/res/Mai.png");
    _weatherMap.insert("强沙尘暴", ":/res/QiangShaChenBao.png");
    _weatherMap.insert("晴", ":/res/Qing.png");
    _weatherMap.insert("沙尘暴", ":/res/ShaChenBao.png");
    _weatherMap.insert("特大暴雨", ":/res/TeDaBaoYu.png");
    _weatherMap.insert("undefined", ":/res/undefined.png");
    _weatherMap.insert("雾", ":/res/Wu.png");
    _weatherMap.insert("小到中雪", ":/res/XiaoDaoZhongXue.png");
    _weatherMap.insert("小到中雨", ":/res/XiaoDaoZhongYu.png");
    _weatherMap.insert("小雪", ":/res/XiaoXue.png");
    _weatherMap.insert("小雨", ":/res/XiaoYu.png");
    _weatherMap.insert("雪", ":/res/Xue.png");
    _weatherMap.insert("扬沙", ":/res/YangSha.png");
    _weatherMap.insert("阴", ":/res/Yin.png");
    _weatherMap.insert("雨", ":/res/Yu.png");
    _weatherMap.insert("雨夹雪", ":/res/YuJiaXue.png");
    _weatherMap.insert("阵雪", ":/res/ZhenXue.png");
    _weatherMap.insert("阵雨", ":/res/ZhenYu.png");
    _weatherMap.insert("中到大雪", ":/res/ZhongDaoDaXue.png");
    _weatherMap.insert("中到大雨", ":/res/ZhongDaoDaYu.png");
    _weatherMap.insert("中雪", ":/res/ZhongXue.png");
    _weatherMap.insert("中雨", ":/res/ZhongYu.png");

    QFile file("D://code//C_Program//qt_learn//weather//citycode.json");
    if (file.open(QIODeviceBase::ReadOnly)) {
        QByteArray byteArray = file.readAll();
        QJsonDocument jsonDocument = QJsonDocument::fromJson(byteArray);
        if (jsonDocument.isArray()) {
            QJsonArray jsonArray = jsonDocument.array();
            foreach (const QJsonValue& jsonValue, jsonArray) {
                if (jsonValue.isObject()) {
                    QJsonObject jsonObj = jsonValue.toObject();
                    _cityCodeMap.insert(jsonObj["city_name"].toString(), jsonObj["city_code"].toString());
                }
            }
        }
        file.close();
    } else {
        qDebug() << "can't open file";
    }
}

QString WeatherNetWork::getCityCode(const QString& city)
{
    auto itr = _cityCodeMap.find(city);
    if (itr != _cityCodeMap.end()) {
        return itr.value();
    } else {
        itr = _cityCodeMap.find(city + "市");
        if (itr != _cityCodeMap.end()) {
            return itr.value();
        } else {
            itr = _cityCodeMap.find(city + "县");
            if (itr != _cityCodeMap.end()) {
                return itr.value();
            } else {
                itr = _cityCodeMap.find(city + "区");
                if (itr != _cityCodeMap.end()) {
                    return itr.value();
                }
            }
        }
    }
    return "";
}

void WeatherNetWork::onNetworkReply(QNetworkReply* reply)
{
    if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 200) {
        return;
    }
    QJsonDocument jsonDocument = QJsonDocument::fromJson(reply->readAll());
    if (jsonDocument.isNull() || !jsonDocument.isObject()) {
        return;
    }

    QJsonObject jsonObj = jsonDocument.object();

    if (jsonObj.contains("aqi") && jsonObj["aqi"].isObject()) {
        QJsonObject aqiObj = jsonObj["aqi"].toObject();
        _parent->_city->setText(aqiObj["city"].toString());
        _parent->_pM25Index->setText(aqiObj["pm25"].toString());
        _parent->_airQualityIndex->setText(aqiObj["air"].toString());
    }

    if (jsonObj.contains("data") && jsonObj["data"].isArray()) {
        QJsonArray jsonArray = jsonObj["data"].toArray();
        for (int i = 0; i < 6; ++i) {
            if (jsonArray[i].isObject()) {
                QJsonObject weatherObj = jsonArray[i].toObject();
                if (i == 0) {
                    _parent->_temperatureText->setText(weatherObj["tem"].toString() + "°");
                    _parent->_weatherText->setText(weatherObj["wea_day"].toString());
                    _parent->_lowHighTemperature->setText(weatherObj["tem2"].toString() + "~" + weatherObj["tem1"].toString() + "°C");
                    _parent->_coldIndex->setText(weatherObj["air_tips"].toString());
                }
                if (weatherObj.contains("win") && weatherObj["win"].isArray()) {
                    QJsonArray winArr = weatherObj["win"].toArray();
                    if (i == 0) {
                        _parent->_windDirection->setText(winArr[0].toString());
                    }
                    _parent->_windDirectionList[i]->setText(winArr[0].toString());
                }
                QString windSpeed = weatherObj["win_speed"].toString();
                if (windSpeed.length() <= 3) {
                    _parent->_windLevelList[i]->setText(windSpeed);
                } else {
                    _parent->_windLevelList[i]->setText(weatherObj["win_speed"].toString().first(3) + "级");
                }
                _parent->_humidityPercent->setText(weatherObj["humidity"].toString());
                _parent->_airQualityList[i]->setText(weatherObj["air_level"].toString());
                _parent->_airQualityList[i]->setStyleSheet(QString("background-color: %1").arg(_qualityMap[weatherObj["air_level"].toString()]));
                _parent->_weekList[i]->setText(weatherObj["week"].toString());
                _parent->_dateList[i]->setText(weatherObj["date"].toString().mid(5, 2) + "/" + weatherObj["date"].toString().right(2));
                _parent->_lowTemp[i] = weatherObj["tem2"].toString().toInt();
                _parent->_highTemp[i] = weatherObj["tem1"].toString().toInt();
                _parent->_weatherTypeList[i]->setText(weatherObj["wea"].toString());
                _parent->_weatherIconList[i]->setPixmap(QPixmap(_weatherMap[weatherObj["wea_day"].toString()]));
                if (i == 0) {
                    _parent->_weatherIcon->setPixmap(QPixmap(_weatherMap[weatherObj["wea_day"].toString()]));
                }
            }
        }
    }
    _parent->_highTempLineChart->update();
    _parent->_lowTempLineChart->update();
}
